package com.itcast.quartz.job;

import org.quartz.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import static com.itcast.quartz.DateAndTimeUtils.dateConvertToLocalDateTime;

/**
 * 默认是无状态，每次调用都会创建一个新的JobDataMap
 * 加注解后是有状态，会对Job进行持久化，保存一些数据信息
 * @author brian
 */
@PersistJobDataAfterExecution
public class HelloJob implements Job {

    public HelloJob() {
        System.out.println("HelloJob constructor...");
    }

    private String jobName;
    private Integer count;

    public void setJobName(String jobName) {
        this.jobName = jobName;
    }

    public void setCount(Integer count) {
        this.count = count;
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        //输出当前时间
        LocalDateTime date = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String dataStr = date.format(formatter);
        //工作内容
        System.out.println("备份数据库的时间是：" + dataStr);

        //获取JobDetail的内容
        JobKey jobKey = context.getJobDetail().getKey();
        System.out.println("任务类的名称（带路金）：" + context.getJobDetail().getJobClass().getName());
        System.out.println("工作任务名称：" + jobKey.getName() + ";工作任务的组：" + jobKey.getGroup());
        //从JobDetail对象中获取jobDataMap的数据
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        String jobDataMessage = jobDataMap.getString("message");
        System.out.println("任务数据的参数值：" + jobDataMessage);

        //从获取Trigger对象中获取jobDataMap的数据
        JobDataMap triggerDataMap = context.getTrigger().getJobDataMap();
        String triggerDataMessage = triggerDataMap.getString("message");
        System.out.println("触发器数据的参数值：" + triggerDataMessage);

        //获取其他内容
        System.out.println("当前任务的执行时间：" + dateConvertToLocalDateTime(context.getFireTime()));
        System.out.println("下一次任务的执行时间：" + dateConvertToLocalDateTime(context.getNextFireTime()).format(formatter));

        //从setter方法中读取jobName值
        System.out.println("jobName：" + jobName);

        //累加count
        ++count;
        //输出count
        System.out.println("count的数量：" + count);
        //将count存放到JobDataMap中
        context.getJobDetail().getJobDataMap().put("count", count);

    }
}
